<?php


namespace app\queue\stomp;


use think\Hook;
use Webman\Stomp\Client;
use app\queue\BaseConsumer;
use common\model\TaskModel;
use common\model\UserModel;
use common\service\TaskService;
use common\service\UserService;
use common\service\OptionsService;
use common\model\ProjectMemberModel;
use common\service\TaskAssembleService;

/**
 * 任务返修 异步通知到关联的人员
 */
class TaskRepairNotifyRelatePeopleConsumer extends BaseConsumer
{
    // 要消费的队列名
    public $queue = 'task_repair_notify_relate_people';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    public function doConsume($data)
    {
        try {

            $hookData = [
                'type' => 'task_repair_notice',
                'data' => [
                    'from_demand_order' => $data['from_demand_order'] ?? false,
                    'changed_id_list' => array_column($data['changed'], 'id'),
                    'need_repair_task_id' => $data['need_repair_task_id'],
                    'relation_note_text' => $data['relation_note']['text'] ?? "",
                ],
            ];
            Hook::listen('task_repair', $hookData);
            return;

            $queryFields = [
                'task.id',
                'task.name',
                'task.executor',
                'task.tenant_id',
                'task.project_id',
                'task.assignee_producer',
                'task.department_id',
                'task.entity_module_id',

                'entity.id',
                'entity.name',
                'entity.initial_episode_code',
                'entity.showings_number',
            ];
            $relatePeopleTasks = model(TaskModel::class)
                ->join('entity on entity.id = task.entity_id')
                ->where(['task.id' => ['IN', array_column($data['changed'], 'id')]])
                ->field(build_complex_query_fields($queryFields, '__'))
                ->select();


            $relatedTasks = model(TaskModel::class)
                ->where(['task.id' => ['IN', array_column($data['changed'], 'id')]])
                ->select();

            // 记录异常通知
            foreach ($relatedTasks as $task) {
                $queueData = [
                    'module_code' => 'task',
                    'type' => 'repair',
                    'info' => $data['relation_note']['text'] ?? '',
                    'data' => $task,
                ];
                Client::send("abnormal_info_store", build_queue_data_with_xu($queueData));
            }

            // 抽取数据
            $userIdList = [];
            $projectIdList = [];
            $departmentIdList = [];
            $tenantIdList = [];
            $needRepairTaskName = '';
            $needRepairTaskData = null;
            foreach ($relatePeopleTasks as &$relatePeopleTask) {
                $relatePeopleTask = separate_complex_query_data($relatePeopleTask, '__');
                $userIdList[$relatePeopleTask['task']['executor']] = $relatePeopleTask['task']['executor'];
                $userIdList[$relatePeopleTask['task']['assignee_producer']] = $relatePeopleTask['task']['assignee_producer'];
                $projectIdList[$relatePeopleTask['task']['project_id']] = $relatePeopleTask['task']['project_id'];
                $departmentIdList[$relatePeopleTask['task']['department_id']] = $relatePeopleTask['task']['department_id'];
                $tenantIdList[$relatePeopleTask['task']['tenant_id']] = $relatePeopleTask['task']['tenant_id'];
                if ($relatePeopleTask['task']['id'] == $data['need_repair_task_id']) {
                    $needRepairTaskName = TaskAssembleService::getInstance()->getNotifyTaskName($relatePeopleTask['entity'], $relatePeopleTask['task']);
                    $needRepairTaskData = $relatePeopleTask;
                }
            }
            unset($departmentIdList[0], $tenantIdList[0], $projectIdList[0]);

            // 项目生产制片查询 组装项目生产制片map
            $projectMemberList = model(ProjectMemberModel::class)
                ->where([
                    'project_id' => ['IN', implode(',', $projectIdList)],
                    'role_code' => TaskService::EXECUTIVE_PRODUCER_CODE,
                ])
                ->field('project_id,user_id')
                ->group('project_id,user_id')
                ->select();
            $userIdList = array_merge($userIdList, array_column($projectMemberList, 'user_id', 'user_id'));
            $projectMemberMap = [];
            foreach ($projectMemberList as $projectMember) {
                $projectMemberMap[$projectMember['project_id']][] = $projectMember['user_id'];
            }
            unset($userIdList[0]);
            // 根据上面的已有user_id 查询当前系统userMap
            $userList = [];
            if (!empty($userIdList)) {
                $userList = model(UserModel::class)->where(['id' => ['IN', implode(',', $userIdList)]])->select();
                $userList = array_column($userList, null, 'id');
            }

            // 根据部门id查询组长 组装部门组长map
            $userDepartmentMap = [];
            if (!empty($departmentIdList)) {
                $filter = [
                    'tenant_id' => ['-in', implode(',', $tenantIdList)],
                    'department_id' => ['-in', implode(',', $departmentIdList)],
                    'role_code' => TaskService::HEADMAN_CODE,
                ];
                $userDepartmentMap = UserService::getInstance()->getDepartmentSaasUserMap($filter);
            }

            unset($relatePeopleTask);

            $templateId = OptionsService::getInstance()->getTaskRemindCommonTemplateId();


            // 遍历每个任务 组长要通知的人员
            foreach ($relatePeopleTasks as $relatePeopleTask) {
                $currentNotifyUserList = [];

                if ($relatePeopleTask['task']['executor'] > 0 && isset($userList[$relatePeopleTask['task']['executor']])) {
                    $currentNotifyUserList[$relatePeopleTask['task']['executor']] = $userList[$relatePeopleTask['task']['executor']];
                }

                if ($relatePeopleTask['task']['assignee_producer'] > 0 && isset($userList[$relatePeopleTask['task']['assignee_producer']])) {
                    $currentNotifyUserList[$relatePeopleTask['task']['assignee_producer']] = $userList[$relatePeopleTask['task']['assignee_producer']];
                }

                if ($relatePeopleTask['task']['department_id'] > 0 && isset($userDepartmentMap[$relatePeopleTask['task']['department_id']])) {
                    foreach ($userDepartmentMap[$relatePeopleTask['task']['department_id']] as $departmentSaasUser) {
                        $currentNotifyUserList[$departmentSaasUser['id']] = $departmentSaasUser;
                    }
                }

                if ($relatePeopleTask['task']['project_id'] > 0 && isset($projectMemberMap[$relatePeopleTask['task']['project_id']])) {
                    foreach ($projectMemberMap[$relatePeopleTask['task']['project_id']] as $projectMemberUserId) {
                        if (isset($userList[$projectMemberUserId])) {
                            $currentNotifyUserList[$projectMemberUserId] = $userList[$projectMemberUserId];
                        }
                    }
                }

                if (empty($currentNotifyUserList)) {
                    continue;
                }

                $taskName = TaskAssembleService::getInstance()->getNotifyTaskName($relatePeopleTask['entity'], $relatePeopleTask['task']);
                // 通知文本组装
                if ($data['need_repair_task_id'] == $relatePeopleTask['task']['id']) {
                    $noteText = '任务' . $taskName . '被返修了';
                } else {
                    if ($relatePeopleTask['entity']['id'] != $needRepairTaskData['entity']['id']) {
                        $relateType = '关联';
                    } else {
                        $relateType = '上游';
                    }
                    $noteText = '任务' . $taskName . '的' . $relateType . $needRepairTaskName . '返修了';
                }

                $notifyParam = [
                    'first' => '任务返修通知',
                    'note_text' => $noteText,
                    'remark' => "请及时查看",
                    'tenant_id' => $relatePeopleTask['task']['tenant_id'],
                    'project_id' => $relatePeopleTask['task']['project_id'],
                    'task_id' => $relatePeopleTask['task']['id'],
                    'module_code' => in_array(module_by_id($relatePeopleTask['task']['entity_module_id'])['code'], ['design', 'level', 'asset']) ? 'asset' : 'shot',
                    'message_key' => 'task_repaired',
                ];

                foreach ($currentNotifyUserList as $currentNotifyUser) {
                    // 异步发送通知
                    Client::send('send_notify_message_v2', build_queue_data_with_xu([
                        "param" => $notifyParam,
                        'receiver' => $currentNotifyUser['union_id'],
                        'template_id' => $templateId,
                        'content_type' => 'card_message',
                        'notice_type' => 'message_task',
                        'is_popup' => 1,
                        'message_key' => $notifyParam['message_key'],
                    ]));
                }
            }
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
